package net.enantena.finappsparty2012;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class CreateEvent extends Activity implements OnClickListener {

	Button nextButton;
	EditText objectiuEditText;
	EditText dataObjectiu;
	SharedPreferences settings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		settings = getSharedPreferences(Data.sharedprefs,
				MODE_PRIVATE);
		String currObjective = settings.getString("objectiu", "-999");
		if (!currObjective.equals("-999")) {
			startActivity(new Intent(CreateEvent.this, Dashboard.class));
		}

		nextButton = (Button) findViewById(R.id.next);
		nextButton.setOnClickListener(this);
		objectiuEditText = (EditText) findViewById(R.id.editText1);
		dataObjectiu = (EditText) findViewById(R.id.datePicker1);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.next:
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("objectiu", objectiuEditText.getText().toString());
			editor.putString("data", dataObjectiu.getText().toString());
			editor.commit();
			Intent intent = new Intent(Intent.ACTION_PICK,
					ContactsContract.Contacts.CONTENT_URI);
			startActivityForResult(intent, 2988);
			break;

		default:
			break;
		}

	}

	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);

		switch (reqCode) {
		case (2988):
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				@SuppressWarnings("deprecation")
				Cursor c = managedQuery(contactData, null, null, null, null);
				if (c.moveToFirst()) {
					String name = c
							.getString(c
									.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					Log.e("cotacte seleccionat", name);

					Pattern emailPattern = Patterns.EMAIL_ADDRESS;
					Account[] accounts = AccountManager.get(
							getApplicationContext()).getAccounts();
					for (Account account : accounts) {
						if (emailPattern.matcher(account.name).matches()) {
							String possibleEmail = account.name;
							new CreateUser().execute(possibleEmail);
						}
					}

					startActivity(new Intent(CreateEvent.this, Dashboard.class));
				}
			}
			break;
		}
	}

	public class CreateUser extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			String mail = params[0];
			Log.e("mail", mail);
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Data.registerUser);

			try {
				JSONObject holder = new JSONObject();
				holder.put("username", mail);
				holder.put("password", mail + "1234");
				holder.put("firstName", mail);
				holder.put("lastName", mail);
				JSONObject address = new JSONObject();
				address.put("street", "#TODO");
				address.put("number", "#TODO");
				address.put("city", "#TODO");
				address.put("postalCode", "#TODO");
				address.put("country", "#TODO");
				holder.put("address", address);

				StringEntity se = new StringEntity(holder.toString());
				httppost.setEntity(se);
				httppost.setHeader("Accept", "application/json");
				httppost.setHeader("Content-type", "application/json");
				HttpResponse response = httpclient.execute(httppost);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent(), "UTF-8"));
				StringBuilder builder = new StringBuilder();
				for (String line = null; (line = reader.readLine()) != null;) {
					builder.append(line).append("\n");
				}
				JSONObject jsonResponse = new JSONObject(builder.toString());
				if (jsonResponse.getString("msg").equals("User already exist")) {

				} else if (!jsonResponse.getString("status").equals("OK")) {
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("userid", jsonResponse.getString("id"));
					editor.commit();
				}
				Log.e("response", builder.toString());

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
	}
}
